package com.powernode.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.constant.QueueConstant;
import com.powernode.domain.ChangeStock;
import com.powernode.domain.Order;
import com.powernode.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class OrderDeadListener {

    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = QueueConstant.ORDER_DEAD_QUEUE)
    public void handlerOrderDeadMsg(Message message, Channel channel) {
        // 获取消息，先查询订单详情
        String messageStr = new String(message.getBody());
        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(messageStr);


        // 获取订单编号
        String orderNum = jsonObject.get("orderNum", String.class);


        // 获取修改商品库存数量
        ChangeStock changeStock = jsonObject.get("changeStock", ChangeStock.class);

        Order order = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNumber, orderNum)
        );

        if (ObjectUtil.isNull(order)) {
            log.error("订单号码无效");
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        // 判断订单已经支付
        if (order.getIsPayed().equals(1)) {
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        // 未支付，调用第三方支付平台的查询接口
        // 从第三方平台获取订单详情，然后再来判断是否已支付，如果第三方已支付则修改订单状态，第三方通知未支付则超时未支付修改订单状态和商品数量回滚

        try {
            orderService.orderRollBack(order, changeStock);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
